package com.atguigu.gulimallcart.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimallcart.feign.ProductFeignService;
import com.atguigu.gulimallcart.interceptor.CartInterceptor;
import com.atguigu.gulimallcart.service.CartService;
import com.atguigu.gulimallcart.to.SkuInfoTo;
import com.atguigu.gulimallcart.vo.Cart;
import com.atguigu.gulimallcart.vo.CartItem;
import com.atguigu.gulimallcart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    ProductFeignService productFeignService;
    @Resource
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String res = (String) cartOps.get(skuId.toString());
        if(StringUtils.isNotBlank(res)){
            //购物车有此商品  修改数量
            CartItem cartItem = JSON.parseObject(res,CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }else {
            CartItem item = new CartItem();
            //1.远程查询当前要添加得商品信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(()->{
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoTo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoTo>() {
                });
                //2.新商品添加到购物车
                item.setCheck(true);
                item.setCount(num);
                item.setImage(info.getSkuDefaultImg());
                item.setTitle(info.getSkuTitle());
                item.setSkuId(skuId);
                item.setPrice(info.getPrice());
            },executor);
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                item.setSkuAttr(values);
            },executor);
            try {
                CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            String cartItem = JSON.toJSONString(item);
            cartOps.put(skuId.toString(),cartItem);
            // 远程查询sku 的组合信息
            return item;
        }

    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(res, CartItem.class);
    }

    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String tempKey = CART_PREFIX+userInfoTo.getUserKey();
        //当前临时用户购物车信息
        List<CartItem> cartItems = getCartItems(tempKey);
        if (userInfoTo.getUserId()!=null) {
            //登录了  把临时购物车信息，添加到当前用户的购物车信息下
            for (CartItem cartItem : cartItems) {
                //添加的时候会找到当前用户
                addToCart(cartItem.getSkuId(),cartItem.getCount());
            }
            //删除临时购物车数据
            System.out.println(tempKey);
            stringRedisTemplate.delete(tempKey);

            //在redis 中查出来反显
            List<CartItem> items = getCartItems(CART_PREFIX + userInfoTo.getUserId());
            cart.setItems(items);
            return cart;
        }
        cart.setItems(cartItems);
        return cart;
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        String o = ops.get(skuId.toString()).toString();
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        cartItem.setCheck(!cartItem.getCheck());
        ops.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void changeNum(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        String o = ops.get(skuId.toString()).toString();
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        cartItem.setCount(num);
        ops.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> currentUserItems() {
        ThreadLocal<UserInfoTo> threadLocal = CartInterceptor.threadLocal;
        UserInfoTo userInfoTo = threadLocal.get();
        if(userInfoTo.getUserId()==null){
            return null;
        }
        List<CartItem> cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserId());
        List<CartItem> collect = cartItems.stream().
                filter(item -> item.getCheck())
                .map(item->{
                    BigDecimal price = productFeignService.getPrice(item.getSkuId());
                    item.setPrice(price);
                    return item;
                })
                .collect(Collectors.toList());
        return collect;
    }

    /**
     * 获取到要操作得购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //通过threadLocal 获取到当前用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if(userInfoTo.getUserId()!=null){
            cartKey = CART_PREFIX+userInfoTo.getUserId();
        }else {
            cartKey = CART_PREFIX+userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        return hashOps;
    }

    private List<CartItem> getCartItems(String key){
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(key);
        List<Object> values = hashOps.values();
        List<CartItem> collect = values.stream().map((obj) -> {
            return JSON.parseObject(obj.toString(), CartItem.class);
        }).collect(Collectors.toList());
        return collect;
    }
}
